// 引入axios
import axios from 'axios';
import { useMainStore } from '@/stores/index';
import qs from 'qs';
import { ElMessage } from 'element-plus';

// 根据环境设置不同的baseUrl
// 开发环境使用代理
// 生产环境直接使用后端地址
const baseUrl = import.meta.env.MODE === 'development' 
  ? '/api' 
  : 'http://8.137.173.171:9090';

const agentUrl = import.meta.env.MODE === 'development' 
  ? '/agent' 
  : 'http://8.137.173.171:8088';

// 获取token
function getToken() {
  return sessionStorage.getItem('token');
}

// 创建axios实例 - API服务
const httpService = axios.create({
  baseURL: baseUrl,
  timeout: 100000000,
  withCredentials: true // 支持发送凭证
});

// 创建axios实例 - Agent服务
const agentService = axios.create({
  baseURL: agentUrl,
  timeout: 100000000,
  withCredentials: true // 支持发送凭证
});

// 添加请求拦截器 - API服务
httpService.interceptors.request.use(function (config) {
  const token = getToken();
  if (token) {
    config.headers['token'] = token; // 设置token到headers中
  }
  return config;
}, function (error) {
  return Promise.reject(error);
});

// 添加请求拦截器 - Agent服务
agentService.interceptors.request.use(function (config) {
  const token = getToken();
  if (token) {
    config.headers['token'] = token; // 设置token到headers中
  }
  return config;
});

// 添加响应拦截器 - API服务
httpService.interceptors.response.use(function (response) {
  return response;
}, function (error) {
  return Promise.reject(error);
});

// 添加响应拦截器 - Agent服务
agentService.interceptors.response.use(function (response) {
  return response;
}, function (error) {
  return Promise.reject(error);
});

/*网络请求部分*/

/*
 *  get请求
 *  url:请求地址
 *  params:参数
 * */
export function get(url, params = {}) {
    return new Promise((resolve, reject) => {
        httpService({
            url: url,
            method: 'get',
            params: params
        }).then(response => {
            resolve(response);
        }).catch(error => {
            reject(error);
        });
    });
}

/*
 *  post请求
 *  url:请求地址
 *  params:参数
 * */
export function post(url, params = {}) {
    return new Promise((resolve, reject) => {
        httpService({
            url: url,
            method: 'post',
            data: params,
        }).then(response => {
            resolve(response);
        }).catch(error => {
            reject(error);
        });
    });
}

/*
 *  agent服务的get请求
 *  url:请求地址
 *  params:参数
 * */
export function agentGet(url, params = {}) {
    return new Promise((resolve, reject) => {
        agentService({
            url: url,
            method: 'get',
            params: params
        }).then(response => {
            resolve(response);
        }).catch(error => {
            reject(error);
        });
    });
}

/*
 *  agent服务的post请求
 *  url:请求地址
 *  params:参数
 * */
export function agentPost(url, params = {}) {
    return new Promise((resolve, reject) => {
        agentService({
            url: url,
            method: 'post',
            data: params,
        }).then(response => {
            resolve(response);
        }).catch(error => {
            reject(error);
        });
    });
}

/*
 *  文件上传
 *  url:请求地址
 *  formData:包含文件和其他参数的FormData对象
 * */
export function fileUpload(url, formData) {
    return new Promise((resolve, reject) => {
        httpService({
            url: url,
            method: 'post',
            data: formData,
            headers: { 'Content-Type': 'multipart/form-data' ,
                token: getToken(),
            }
        }).then(response => {
            resolve(response);
        }).catch(error => {
            reject(error);
        });
    });
}

/*
 *  新增：专属文件上传方法
 *  url:请求地址
 *  file:文件对象
 *  otherParams:其他参数（可选）
 * */
export function customFileUpload(url, file, otherParams = {}) {
    return new Promise((resolve, reject) => {
        let formData = new FormData();
        formData.append('image', file);

        // 添加其他参数到formData
        for (let key in otherParams) {
            if (otherParams.hasOwnProperty(key)) {
                formData.append(key, otherParams[key]);
            }
        }

        httpService({ // 使用 httpService 而不是 axios
            url: url,
            method: 'post',
            data: formData,
            headers: { 'Content-Type': 'multipart/form-data' }
        }).then(response => {
            resolve(response);
        }).catch(error => {
            reject(error);
        });
    });
}

/*
 *  delete请求
 *  url: 请求地址
 *  config: 配置对象，可以包含数据和其他配置
 * */
export function deleteRequest(url, config = {}) {
    return new Promise((resolve, reject) => {
        httpService({
            url: url,
            method: 'delete',
            ...config
        }).then(response => {
            resolve(response);
        }).catch(error => {
            reject(error);
        });
    });
}

/*
 *  put请求
 *  url: 请求地址
 *  params: 参数
 * */
export function put(url, params = {}) {
    return new Promise((resolve, reject) => {
        httpService({
            url: url,
            method: 'put',
            data: params
        }).then(response => {
            resolve(response);
        }).catch(error => {
            reject(error);
        });
    });
}

export function getServerUrl() {
    return baseUrl;
}

export function getAgentUrl() {
    return agentUrl;
}

export default {
    get,
    post,
    fileUpload,
    customFileUpload, // 新增的方法
    getServerUrl,
    getAgentUrl,
    deleteRequest,
    put,
    agentGet,
    agentPost
}
